package day1.homework.three;

import java.util.Arrays;

/**
 * @创建人 MBY381
 * @创建时间 2022/6/27 15:42
 * @描述 暂无
 */
public class StackStimulator<T> {
    private Object[] data;
    private static final int DEFAULT_CAPACITY = 10;
    private int capacity;
    private int index = 0;

    StackStimulator() {
        super();
        capacity = DEFAULT_CAPACITY;
    }

    StackStimulator(int capacity) {
        super();
        this.capacity = capacity;
        data = new Object[capacity];
    }


    public void push(T t) {
        if(isEmpty()){
            initCapacity();
        }
        if (index >= capacity - 1) {
            expandCapacity();
        }
        data[index] = t;
        index++;
        System.out.println("index+"+index);
    }

    public T pop() {
        if (!isEmpty()) {
            T answer=(T) data[index-1];
            data[index-1] = null;
            index--;
            return answer;
        } else {
            return null;
        }
    }

    public T peek() {
        if (!isEmpty()) {
            return (T) data[index-1];
        } else {
            return null;
        }
    }

    public boolean isEmpty() {
        return index == 0;
    }

    private void expandCapacity() {
        capacity = capacity << 1;
        data = Arrays.copyOf(data, capacity);
    }

    private void initCapacity() {
        capacity = DEFAULT_CAPACITY;
        data = new Object[capacity];
    }

    @Override
    public String toString() {
        int tag = 0;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("size: ").append(this.size()).append(" [ ");
        while (tag < capacity && data[tag] != null) {
            stringBuilder.append(data[tag].toString()).append(", ");
            tag++;
        }
        stringBuilder.append(" ]");
        return stringBuilder.toString();
    }

    public int size() {
        return this.index;
    }
}
